//
//  FQDSettingsViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/8/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDSettingsViewController.h"
#import "FQDUserSettingViewController.h"
#import "FQDNavigationController.h"
#import "FQDMobileRegisterViewController.h"
#import "FQDSettingOption.h"
#import "FQDNavigationView.h"
#import "FQDPlainSettingCell.h"
#import "FQDFontSettingCell.h"
#import "FQDSwitchSettingCell.h"
#import "FQDAccountManager.h"
#import "FQDRestModel.h"
#import "MBProgressHUD+FQDExtension.h"

#import "Masonry.h"

@interface FQDSettingsViewController () <UITableViewDelegate, UITableViewDataSource>

// 设置选项TableView
@property (nonatomic, strong) UITableView *settingTableView;
// 设置选项
@property (nonatomic, strong) NSArray *optionList;
// “「 好奇驱动你的世界 」”文本
@property (nonatomic, strong) UILabel *wordLabel;

@end

@implementation FQDSettingsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupOptions];
    [self setupNavigationView];
    [self setupTableView];
    [self setupNotifications];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupOptions
{
    // Section 0
    BOOL isLogined = [[FQDAccountManager sharedManager] isLogined];
    NSString *accountTitle = (isLogined) ? @"账号设置" : @"登录或注册";
    FQDSettingOption *accountOption = [FQDSettingOption optionWithTitle:accountTitle];
    accountOption.cellClass = [FQDPlainSettingCell class];
    [accountOption setSelectionBlock:^{
        if (isLogined) {
            FQDUserSettingViewController *usVC = [[FQDUserSettingViewController alloc] init];
            usVC.blurBgImage = self.blurBgImage;
            [self.navigationController pushViewController:usVC animated:YES];
        } else {
            FQDMobileRegisterViewController *mrVC = [[FQDMobileRegisterViewController alloc] init];
            mrVC.blurBgImage = self.blurBgImage;
            
            FQDNavigationController *navController = [[FQDNavigationController alloc] init];
            navController.navigationBarHidden = YES;
            navController.viewControllers = @[mrVC];
            [self presentViewController:navController animated:YES completion:nil];
        }
    }];
    
    NSArray *section0 = @[accountOption];
    
    // Section 1
    FQDFontSizeCategory sizeCategory = [self currentFontSizeCategory];
    FQDSettingOption *fontSizeOption = [FQDSettingOption optionWithTitle:@"字体大小"];
    fontSizeOption.cellClass = [FQDFontSettingCell class];
    fontSizeOption.value = @(sizeCategory);
    
    NSArray *section1 = @[fontSizeOption];
    
    // Section 2
    FQDSettingOption *pushMessageOption = [FQDSettingOption optionWithTitle:@"推送消息"];
    pushMessageOption.detail = @"未开启";
    pushMessageOption.cellClass = [FQDPlainSettingCell class];
    
    NSMutableArray *section2 = [NSMutableArray arrayWithObject:pushMessageOption];
    if (isLogined) {
        FQDUser *user = [[FQDAccountManager sharedManager] currentUser];
        FQDSettingOption * remindSubUpdateOption = [FQDSettingOption optionWithTitle:@"接收订阅更新提醒"];
        remindSubUpdateOption.cellClass = [FQDSwitchSettingCell class];
        remindSubUpdateOption.value = @(user.openColumnPush);
        [section2 addObject:remindSubUpdateOption];
        
        FQDSettingOption *remindCommentOption = [FQDSettingOption optionWithTitle:@"接收评论通知"];
        remindCommentOption.cellClass = [FQDSwitchSettingCell class];
        remindCommentOption.value = @(user.openCommentPush);
        [section2 addObject:remindCommentOption];
    }
    
    // Section 3
    FQDSettingOption *rankOption = [FQDSettingOption optionWithTitle:@"给我们打分"];
    rankOption.cellClass = [FQDPlainSettingCell class];
    [rankOption setSelectionBlock:^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:FQDAppRankURL]];
    }];
    
    FQDSettingOption *feedbackOption = [FQDSettingOption optionWithTitle:@"反馈意见"];
    feedbackOption.cellClass = [FQDPlainSettingCell class];
    [rankOption setSelectionBlock:^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:FQDAppRankURL]];
    }];
    
    FQDSettingOption *clearCacheOption = [FQDSettingOption optionWithTitle:@"清除缓存"];
    clearCacheOption.cellClass = [FQDPlainSettingCell class];
    [clearCacheOption setSelectionBlock:^{
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定清除本地缓存？"
                                              message:@""
                                              preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * _Nonnull action) {
            [self clearCache];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:confirmAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }];
    
    NSArray *section3 = @[rankOption, feedbackOption, clearCacheOption];
    
    self.optionList = @[section0, section1, section2, section3];
}

- (void)setupNavigationView
{
    self.navView.titleLabel.text = @"设置";
}

- (void)setupTableView
{
    CGSize viewSize = self.view.bounds.size;
    CGSize navSize = self.navView.frame.size;
    CGRect tableViewRect = CGRectMake(0, navSize.height, viewSize.width, viewSize.height - navSize.height);
    self.settingTableView = [[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStyleGrouped];
    self.settingTableView.backgroundColor = [UIColor clearColor];
    self.settingTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    self.settingTableView.delegate = self;
    self.settingTableView.dataSource = self;
    [self.view addSubview:self.settingTableView];
    
    self.settingTableView.rowHeight = UITableViewAutomaticDimension;
    self.settingTableView.estimatedRowHeight = 45.0f;
    
    [self.settingTableView registerClass:[FQDPlainSettingCell class]
                  forCellReuseIdentifier:[FQDPlainSettingCell reuseId]];
    [self.settingTableView registerClass:[FQDFontSettingCell class]
                  forCellReuseIdentifier:[FQDFontSettingCell reuseId]];
    [self.settingTableView registerClass:[FQDSwitchSettingCell class]
                  forCellReuseIdentifier:[FQDSwitchSettingCell reuseId]];

}

- (void)setupNotifications
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(userInfoDidChange:)
                          name:FQDAccountUserInfoDidChangeNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(fontSizeCategoryDidChange:)
                          name:FQDFontSizeCategoryDidChangeNotification object:nil];
}

- (FQDFontSizeCategory)currentFontSizeCategory
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSNumber *preferFontSize = [userDefaults objectForKey:kQDailyFontSizeCategoryUserDefaultsKey];
    FQDFontSizeCategory sizeCategory = (preferFontSize == nil) ? FQDFontSizeCategoryMiddle : [preferFontSize integerValue];
    return sizeCategory;
}

- (void)updateWordLabelFont
{
     NSDictionary *fontSizeDict = @{
        @(FQDFontSizeCategorySmall) : @(FQDFontSizeSmall),
        @(FQDFontSizeCategoryMiddle) : @(FQDFontSizeMiddle),
        @(FQDFontSizeCategoryLarge) : @(FQDFontSizeLarge),
    };
    
    FQDFontSizeCategory sizeCategory = [self currentFontSizeCategory];
    CGFloat fontSize = [fontSizeDict[@(sizeCategory)] floatValue];
    self.wordLabel.font = FQDRegularFontWithSize(fontSize);
}

#pragma mark - Event response
- (void)clearCache
{
    NSURL *url = [NSURL URLWithString:@"http://app3.qdaily.com"];
    if (url) {
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
        for (int i = 0; i < [cookies count]; i++) {
            NSHTTPCookie *cookie = (NSHTTPCookie *)[cookies objectAtIndex:i];
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
            
        }
    }
    [MBProgressHUD showMessage:@"清除缓存成功"];
}


#pragma mark - Notifications
- (void)userInfoDidChange:(NSNotification *)note
{
    [self setupOptions];
    [self.settingTableView reloadData];
}

- (void)fontSizeCategoryDidChange:(NSNotification *)note
{
    [self updateWordLabelFont];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.optionList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.optionList[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FQDSettingOption *option = self.optionList[indexPath.section][indexPath.row];
    Class cellClass = option.cellClass;
    UITableViewCell<FQDSettingCellProtocol> *cell =
    [tableView dequeueReusableCellWithIdentifier:[cellClass reuseId] forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.option = option;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FQDSettingOption *option = self.optionList[indexPath.section][indexPath.row];
    if (option.selectionBlock) {
        option.selectionBlock();
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return self.wordLabel;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return 64.0f;
    }
    return 0;
}

#pragma mark - Getters and Setters
- (UILabel *)wordLabel
{
    if (!_wordLabel) {
        CGSize tableViewSize = self.settingTableView.frame.size;
        CGRect wordFrame = CGRectMake(0, 0, tableViewSize.width, 64.0f);
        UILabel *wordLabel = [[UILabel alloc] initWithFrame:wordFrame];
        wordLabel.font = FQDRegularFontWithSize(18.0f);
        wordLabel.textColor = [UIColor whiteColor];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"「 好奇驱动你的世界 」";
        wordLabel.alpha = 0.7f;
        _wordLabel = wordLabel;
    }
    return _wordLabel;
}

@end
